//Copyright (c) 2006-2007 Microsoft Corporation.  All rights reserved
using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;

using InvocationFramework.Common.Instrumentation;
using InvocationFramework.Common.Resources;

namespace InvocationFramework.Adapters.WebServices
{
    /// <summary>
    /// </summary>
    /// <author>Rodolfo Finochietti 04/12/2006 20.31</author>
    internal static class ProxyAssemblyCache
    {
        #region Constants

        private const string ProxyName = "InvocationFramework_WebServiceProxy_{0}_Temp.dll";
        
        #endregion

        #region Public Methods

        public static Assembly GetProxy( string wsdlLocation )
        {
            string path = Path.Combine( Path.GetTempPath( ), GetProxyName( wsdlLocation ) );

            if ( File.Exists( path ) )
            {
                TraceHelper.Verbose( Texts.ProxyAssemblyCacheProxyInCache, wsdlLocation );
                return Assembly.LoadFrom( path );
            }
            else
            {
                TraceHelper.Verbose( Texts.ProxyAssemblyCacheProxyNotInCache, wsdlLocation );
                return null;
            }
        }

        public static void AddProxy( string wsdlLocation, string proxyAssemblyPath )
        {
            string newEntryPath = Path.Combine( Path.GetDirectoryName( proxyAssemblyPath ), GetProxyName( wsdlLocation ) );
            File.Copy( proxyAssemblyPath, newEntryPath );

            TraceHelper.Verbose( Texts.ProxyAssemblyCacheProxyNewEntryAdded, wsdlLocation, newEntryPath );
        }

        public static void ClearCache( )
        {
            DirectoryInfo di = new DirectoryInfo( GetCachePath( ) );
            FileInfo[] dllFiles = di.GetFiles( String.Format( CultureInfo.InvariantCulture, ProxyName, "*" ) );

            foreach ( FileInfo fi in dllFiles )
                fi.Delete( );

            TraceHelper.Verbose( Texts.ProxyAssemblyCacheProxyClearCache );
        }

        public static string GetCachePath( )
        {
            return Path.GetTempPath( );
        }

        #endregion
        
        #region Private Methods

        private static string GetProxyName( string wsdlLocation )
        {
            return String.Format( CultureInfo.InvariantCulture, ProxyName, wsdlLocation.GetHashCode( ) );
        }
        
        #endregion
    }
}